<template>
  <div class="blind-box-edit">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ blind_box_id ? '编辑盲盒' : '创建盲盒' }}</span>
          <el-button @click="handleBack">返回</el-button>
        </div>
      </template>

      <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
        <el-tabs v-model="activeTab">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-form-item label="盲盒名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入盲盒名称" />
            </el-form-item>

            <el-form-item label="封面图" prop="image">
              <el-image @click="chooseCoverImage" :src="VITE_URL + '/storage/' + formData.image">
                <template #placeholder>
                  <div class="image-slot">Loading<span class="dot">...</span></div>
                </template>
                <template #error>
                  <div @click="chooseCoverImage" class="image-slot">
                    <el-icon><Plus /></el-icon>
                  </div>
                </template>
              </el-image>
              <el-input type="hidden" v-model="formData.image" />
            </el-form-item>

            <el-form-item label="盲盒描述">
              <el-input 
                v-model="formData.description" 
                type="textarea" 
                :rows="4"
                placeholder="请输入盲盒描述"
              />
            </el-form-item>

            <el-form-item label="盲盒价格" prop="price">
              <el-input-number v-model="formData.price" :min="0" :precision="2" />
            </el-form-item>

            <el-form-item label="库存数量">
              <el-input-number v-model="formData.stock" :min="-1" />
              <span style="margin-left: 10px; color: #909399;">-1表示不限制库存</span>
            </el-form-item>

            <el-form-item label="每人限购">
              <el-input-number v-model="formData.limit_per_user" :min="0" />
              <span style="margin-left: 10px; color: #909399;">0表示不限制</span>
            </el-form-item>

            <el-form-item label="开始时间">
              <el-date-picker
                v-model="formData.start_time"
                type="datetime"
                placeholder="选择开始时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>

            <el-form-item label="结束时间">
              <el-date-picker
                v-model="formData.end_time"
                type="datetime"
                placeholder="选择结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>

            <el-form-item label="排序">
              <el-input-number v-model="formData.sort_order" :min="0" />
            </el-form-item>

            <el-form-item label="状态">
              <el-radio-group v-model="formData.status">
                <el-radio :label="1">上架</el-radio>
                <el-radio :label="0">下架</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-tab-pane>

          <!-- 奖品配置 -->
          <el-tab-pane label="奖品配置" name="prizes">
            <el-button type="primary" @click="handleAddPrize" style="margin-bottom: 20px;">
              添加奖品
            </el-button>

            <el-alert 
              title="奖品概率说明：所有奖品的概率总和应为100，系统会根据概率随机抽取奖品" 
              type="info" 
              :closable="false"
              style="margin-bottom: 20px;"
            />

            <el-table :data="formData.prizes" border stripe>
              <el-table-column label="奖品图片" width="100">
                <template #default="scope">
                  <el-image @click="choosePrizeImage(scope.$index)" :src="VITE_URL + '/storage/' + scope.row.prize_image" class="prize-image-wrapper">
                    <template #placeholder>
                      <div class="image-slot">Loading<span class="dot">...</span></div>
                    </template>
                    <template #error>
                      <div @click="choosePrizeImage(scope.$index)" class="image-slot">
                        <el-icon><Plus /></el-icon>
                      </div>
                    </template>
                  </el-image>
                </template>
              </el-table-column>

              <el-table-column label="奖品类型" width="120">
                <template #default="scope">
                  <el-select v-model="scope.row.prize_type" placeholder="请选择">
                    <el-option label="商品" value="goods" />
                    <el-option label="优惠券" value="coupon" />
                    <el-option label="积分" value="points" />
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column label="奖品名称" min-width="200">
                <template #default="scope">
                  <el-select 
                    v-model="scope.row.prize_id" 
                    placeholder="请选择奖品" 
                    filterable
                    clearable
                    style="width: 100%"
                    @change="handlePrizeChange(scope.row, scope.$index)"
                  >
                    <el-option
                      v-for="item in productList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                  <div style="margin-top: 5px; font-size: 12px; color: #999;">
                    当前奖品名称: {{ scope.row.prize_name }}
                  </div>
                </template>
              </el-table-column>

              <el-table-column label="关联ID" width="100" v-if="false">
                <template #default="scope">
                  <el-input-number v-model="scope.row.prize_id" :min="0" />
                </template>
              </el-table-column>

              <el-table-column label="奖品价值" width="120">
                <template #default="scope">
                  <el-input v-model="scope.row.prize_value" placeholder="如: 100积分" />
                </template>
              </el-table-column>

              <el-table-column label="等级" width="100">
                <template #default="scope">
                  <el-select v-model="scope.row.prize_level" placeholder="请选择">
                    <el-option label="SSR" value="SSR" />
                    <el-option label="SR" value="SR" />
                    <el-option label="R" value="R" />
                    <el-option label="N" value="N" />
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column label="概率(%)" width="180">
                <template #default="scope">
                  <el-input-number v-model="scope.row.probability" :min="0" :max="100" :precision="2" />
                </template>
              </el-table-column>

              <el-table-column label="库存" width="180">
                <template #default="scope">
                  <el-input-number v-model="scope.row.total_stock" :min="-1" />
                </template>
              </el-table-column>

              <el-table-column label="排序" width="180">
                <template #default="scope">
                  <el-input-number v-model="scope.row.sort_order" :min="0" />
                </template>
              </el-table-column>

              <el-table-column label="状态" width="100">
                <template #default="scope">
                  <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" />
                </template>
              </el-table-column>

              <el-table-column label="操作" width="100">
                <template #default="scope">
                  <el-button size="small" type="danger" @click="handleRemovePrize(scope.$index)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <div style="margin-top: 20px; color: #909399;">
              当前概率总和: <strong :style="{ color: totalProbability === 100 ? '#67c23a' : '#f56c6c' }">
                {{ totalProbability }}%
              </strong>
              <span v-if="totalProbability !== 100" style="color: #f56c6c; margin-left: 10px;">
                (建议设置为100%)
              </span>
            </div>
          </el-tab-pane>
        </el-tabs>

        <el-form-item style="margin-top: 30px;">
          <el-button type="primary" @click="handleSubmit" :loading="submitting">保存</el-button>
          <el-button @click="handleBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 文件管理器 -->
    <FileManager :FileManagerData="FileManagerData" @express="handleImageSelect" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
import FileManager from '../Common/file-manager.vue'

const VITE_URL = (window as any).VITE_URL
const router = useRouter()
const route = useRoute()

const blind_box_id = ref(0)
const activeTab = ref('basic')
const submitting = ref(false)
const formRef = ref()

// 文件管理器数据
const FileManagerData = ref({
  visible: false,
  imageType: '', // 'cover' 或 'prize'
  prizeIndex: -1 // 当选择奖品图片时，记录索引
})

const formData = ref({
  name: '',
  description: '',
  image: '',
  price: 0,
  stock: -1,
  limit_per_user: 0,
  start_time: '',
  end_time: '',
  status: 1,
  sort_order: 0,
  prizes: [] as any[]
})

// 商品列表
const productList = ref<Array<{value: number, label: string}>>([])

const rules = {
  name: [{ required: true, message: '请输入盲盒名称', trigger: 'blur' }],
  price: [{ required: true, message: '请输入盲盒价格', trigger: 'blur' }],
  image: [{ required: true, message: '请上传封面图', trigger: 'change' }]
}

// 计算总概率
const totalProbability = computed(() => {
  return formData.value.prizes.reduce((sum, prize) => sum + (prize.probability || 0), 0)
})

// 获取盲盒详情
const getBlindBoxInfo = async () => {
  try {
    const url = `${VITE_URL}/admin.blindBox/info?blind_box_id=${blind_box_id.value}`
    const res = await axios.get(url)
    if (res.data.status === 0) {
      const info = res.data.blind_box
      formData.value = {
        name: info.name,
        description: info.description || '',
        image: info.image,
        price: parseFloat(info.price),
        stock: parseInt(info.stock),
        limit_per_user: parseInt(info.limit_per_user),
        start_time: info.start_time,
        end_time: info.end_time,
        status: parseInt(info.status),
        sort_order: parseInt(info.sort_order),
        prizes: info.prizes || []
      }
    }
  } catch (error) {
    ElMessage.error('获取盲盒信息失败')
  }
}

// 选择封面图
const chooseCoverImage = () => {
  FileManagerData.value.visible = true
  FileManagerData.value.imageType = 'cover'
  FileManagerData.value.prizeIndex = -1
}

// 选择奖品图片
const choosePrizeImage = (index: number) => {
  FileManagerData.value.visible = true
  FileManagerData.value.imageType = 'prize'
  FileManagerData.value.prizeIndex = index
}

// 处理图片选择
const handleImageSelect = (data: any) => {
  if (data.image) {
    if (FileManagerData.value.imageType === 'cover') {
      formData.value.image = data.image.path
    } else if (FileManagerData.value.imageType === 'prize' && FileManagerData.value.prizeIndex >= 0) {
      formData.value.prizes[FileManagerData.value.prizeIndex].prize_image = data.image.path
    }
  }
}

// 添加奖品
const handleAddPrize = () => {
  formData.value.prizes.push({
    prize_type: 'goods',
    prize_id: 0,
    prize_name: '',
    prize_image: '',
    prize_value: '',
    probability: 0,
    total_stock: -1,
    remain_stock: -1,
    prize_level: 'N',
    sort_order: 0,
    status: 1
  })
}

// 删除奖品
const handleRemovePrize = (index: number) => {
  formData.value.prizes.splice(index, 1)
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()

    if (formData.value.prizes.length === 0) {
      ElMessage.warning('请至少添加一个奖品')
      return
    }

    submitting.value = true

    const url = `${VITE_URL}/admin.blindBox/edit`
    const postData = new FormData()
    
    postData.append('blind_box_id', blind_box_id.value.toString())
    postData.append('name', formData.value.name)
    postData.append('description', formData.value.description)
    postData.append('image', formData.value.image)
    postData.append('price', formData.value.price.toString())
    postData.append('stock', formData.value.stock.toString())
    postData.append('limit_per_user', formData.value.limit_per_user.toString())
    postData.append('start_time', formData.value.start_time || '')
    postData.append('end_time', formData.value.end_time || '')
    postData.append('status', formData.value.status.toString())
    postData.append('sort_order', formData.value.sort_order.toString())
    postData.append('prizes', JSON.stringify(formData.value.prizes))

    const res = await axios.post(url, postData)
    
    if (res.data.status === 0) {
      ElMessage.success('保存成功')
      router.push('/main/blindbox/list')
    } else {
      ElMessage.error(res.data.message || '保存失败')
    }
  } catch (error) {
    console.error(error)
  } finally {
    submitting.value = false
  }
}

// 返回
const handleBack = () => {
  router.back()
}

// 获取商品列表
const getProductList = async () => {
  try {
    const url = `${VITE_URL}/admin.design.diy/product?status=1`
    const res = await axios.get(url)
    productList.value = res.data.map((item: any) => ({
      value: item.id,
      label: item.name
    }))
  } catch (error) {
    ElMessage.error('获取商品列表失败')
  }
}

// 处理奖品选择变化
const handlePrizeChange = (row: any, index: number) => {
  // 根据选择的商品ID查找商品名称
  const selectedProduct = productList.value.find(item => item.value === row.prize_id)
  if (selectedProduct) {
    row.prize_name = selectedProduct.label
  } else {
    row.prize_name = ''
  }
}

onMounted(() => {
  if (route.query.blind_box_id) {
    blind_box_id.value = parseInt(route.query.blind_box_id as string)
    getBlindBoxInfo()
  }
  // 获取商品列表
  getProductList()
})
</script>

<style scoped>
.blind-box-edit {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-image {
  width: 148px;
  height: 148px;
  cursor: pointer;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}

.el-image:hover {
  border-color: #409eff;
}

.prize-image-wrapper {
  width: 60px;
  height: 60px;
  cursor: pointer;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}

.prize-image-wrapper:hover {
  border-color: #409eff;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
  cursor: pointer;
}

.image-slot .el-icon {
  font-size: 30px;
}
</style>
